﻿//Force setting jQuery support cross domain.
//This line mostly has effective in IE
jQuery.support.cors = true;

jQuery.fn.getCheckboxVal = function () {
    var vals = [];
    var i = 0;
    this.each(function () {
        vals[i++] = jQuery(this).val();
    });
    return vals;
}
// param filter
var alertFilter = new Object();
var alertnames = new Array();
var messagebodys = new Array();
var campaignids = new Array();
var countryids = new Array();
var languageids = new Array();
var arrText2 = new Array();

var url = location.href;
var arrPage = url.split("#");
//get campagn list filter
var userId = "";
userId = readCookie("userId");
if (userId == "") {
    window.location.href = '../Profile/Login/';
}
$(document).ready(function () {
    $('select.select_long').customStyle();

    getListCampain();

    var view = "week";

    var DATA_FEED_URL = 'Alert';
    var URL_DATA = "";
    var PAGE = 'Alert';
    if (arrPage[arrPage.length - 1] == "Alert") {
        URL_DATA = gb_servicePath + 'alertinstance/list/summary.json';
        var date1 = new Date();
        PAGE = "Alert";
        alertFilter.startdate = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + '01' + ' 00:00:00';
        $('#backpage').html('Back to Alerts Dashboard');
        $('#backpage').click(function (e) {
            window.location.replace('AlertLibrary');
        });
    }
    else if (arrPage[arrPage.length - 1] == "PVQ") {
        URL_DATA = gb_servicePath + 'text2/list/summary.json';
        PAGE = "PVQ";
        var Text2ComponentIDs = new Array();
        var date1 = new Date();
        Text2ComponentIDs.push('2');
        Text2ComponentIDs.push('3');
        Text2ComponentIDs.push('4');
        alertFilter.startdate = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + '01' + ' 00:00:00';
        alertFilter.Text2ComponentIDs = Text2ComponentIDs;
        $('#backpage').html('Back to PVQs Dashboard');
        $('#backpage').click(function (e) {
            window.location.replace('PVQLibrary');
        });
    }
    else if (arrPage[arrPage.length - 1] == "Win") {
        //alert('['+arrPage[arrPage.length - 1]+']');
        URL_DATA = gb_servicePath + 'text2/list/summary.json';
        PAGE = "Win";
        var Text2ComponentIDs = new Array();
        var date1 = new Date();
        Text2ComponentIDs.push('5');
        alertFilter.startdate = date1.getFullYear() + '-' + (date1.getMonth() + 1) + '-' + '01' + ' 00:00:00';
        alertFilter.Text2ComponentIDs = Text2ComponentIDs;
        $('#backpage').html('Back to Win Dashboard');
        $('#backpage').click(function (e) {
            window.location.replace('WinLibrary');
        });
    }
    var op = {
        view: view,
        theme: 3,
        height: 420,
        showday: new Date(),
        EditCmdhandler: Edit,
        DeleteCmdhandler: Delete,
        ViewCmdhandler: View,
        onWeekOrMonthToDay: wtd,
        onBeforeRequestData: cal_beforerequest,
        onAfterRequestData: cal_afterrequest,
        onRequestDataError: cal_onerror,
        autoload: true,
        url: URL_DATA,
        quickAddUrl: DATA_FEED_URL + "/addEvent",
        quickUpdateUrl: DATA_FEED_URL + "/updateEvent",
        quickDeleteUrl: DATA_FEED_URL + "/removeEvent",
        filter: alertFilter,
        viewpage: PAGE
    };
    var $dv = $("#calhead");
    var _MH = document.documentElement.clientHeight;
    var dvH = $dv.height() + 2;
    //op.height = _MH - dvH;
    op.eventItems = [];

    var p = $("#gridcontainer").bcalendar(op).BcalGetOp();
    if (p && p.datestrshow) {
        updateDate(p.datestrshow, p.view);
    }

    // Function Get List Campain
    function getListCampain() {
        $("#listCampainTemplate").css("display", "none");
        $.getJSON(gb_servicePath + '/campaign/list/summary.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        var listcampaigns = "<span>Legend:</span>";
                        $.each(json1.ReturnData, function (i, val) {
                            var o = $("#listCampainTemplate").clone();
                            $(o).css("display", "block");
                            $(o).find("input").attr("value", val.Name);
                            $(o).find("input").attr("name", val.Id);
                            $(o).attr("id", val.Id);
                            $(o).find("span").html(val.Name);
                            $(".list_campaign_cb").append(o);
                            listcampaigns = listcampaigns + "<span style=\"color:" + val.ColorCode + "\">" + val.Name + "</span>";
                        });
                        $('.calendar_color_guide').html(listcampaigns); // add list campaign to footer
                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            setupLabel();
                        });
                        $('.list_campaign_cb').jScrollPane();
                    }
                    getListCountries();
                });
    }
    // Get Function Get List Countries
    function getListCountries() {
        $("#listCountriesTemplate").css("display", "none");
        $("#listLanguageTemplate").css("display", "none");
        $.getJSON(gb_servicePath + '/countrypreference/list.json',
                function (json1) {
                    if (json1.StatusCode == 200) {
                        var strLangIdAdded = "";
                        var langId;
                        $.each(json1.ReturnData, function (i, val) {
                            // check if alredy add country in combobox
                            if ($("#country" + val.Country.Id).length == 0) {
                                var o = $("#listCountriesTemplate").clone();
                                $(o).css("display", "block");
                                $(o).find("input").attr("value", val.Country.Name);
                                $(o).find("input").attr("name", val.Country.Id);
                                $(o).find("input").addClass("case_main");
                                $(o).attr("id", "country" + val.Country.Id);
                                $(o).attr("value", val.Country.Id);
                                $(o).find("span").html(val.Country.Name);
                                $(".countries #list_countries").append(o);
                                langId = val.Language.Id;
                            } if (strLangIdAdded.indexOf(langId) < 0) {
                                //hasn't added langId yet
                                var olag = $("#listLanguageTemplate").clone();
                                olag.css("display", "block");
                                olag.find("input").attr("value", val.Language.Name);
                                olag.find("input").attr("name", val.Language.Id);
                                olag.find("input").addClass("case_main");
                                olag.attr("id", val.Language.Id);
                                olag.attr("name", val.Language.Id);
                                olag.find("span").html(val.Language.Name);
                                $(".list_language").append(olag);
                                strLangIdAdded += langId + ";";

                            }


                        });
                        $('.label_check, .label_radio, .label_check_ip').click(function () {
                            setupLabel();
                        });
                        $('.list_countries').jScrollPane();
                    }
                });
    }
    // End Get Function Get List Countries
    function cal_beforerequest(type) {
        var t = "Loading data...";
        switch (type) {
            case 1:
                t = "Loading data...";
                break;
            case 2:
            case 3:
            case 4:
                t = "The request is being processed ...";
                break;
        }
        $("#errorpannel").hide();
        $("#loadingpannel").html(t).show();
    }
    function cal_afterrequest(type) {
        switch (type) {
            case 1:
                $("#loadingpannel").hide();
                var p = $("#gridcontainer").BcalGetOp();
                if (p && p.datestrshow) {
                    updateDate(p.datestrshow, p.view);
                }
                break;
            case 2:
            case 3:
            case 4:
                $("#loadingpannel").html("Success!");
                window.setTimeout(function () { $("#loadingpannel").hide(); }, 2000);
                break;
        }
        $("#tgnowptr").hide();
    }
    function cal_onerror(type, data) {
        $("#errorpannel").show();
    }
    function Edit(data) {
        var eurl = "edit.php?id={0}&start={2}&end={3}&isallday={4}&title={1}";
        if (data) {
            var url = StrFormat(eurl, data);
            OpenModelWindow(url, { width: 600, height: 400, caption: "Manage  The Calendar", onclose: function () {
                $("#gridcontainer").reload();
            }
            });
        }
    }
    function View(data) {
        var str = "";

        $.each(data, function (i, item) {
            str += "[" + i + "]: " + item + "\n";
        });
        //alert(str);
    }
    function Delete(data, callback) {
        $.alerts.okButton = "Ok";
        $.alerts.cancelButton = "Cancel";
        hiConfirm("Are You Sure to Delete this Event", 'Confirm', function (r) { r && callback(0); });
    }
    function wtd(p) {
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, p.view);
        }
        $("#nav_ca span.selected").each(function () {
            $(this).removeClass("selected");
        })
        $("#btnDay").addClass("selected");
    }
    //to show day view
    $("#btnDay").click(function (e) {
        //document.location.href="#day";
        $("#nav_ca span.selected").each(function () {
            $(this).removeClass("selected");
        })
        $(this).addClass("selected");
        $("#gridcontainer").css('display', 'block');
        $("#listcontainer").css('display', 'none');
        $('#dvtec').jScrollPane({ animateScroll: true });
        $('#dvtec').css('height', '380px');
        var p = $("#gridcontainer").swtichView("day").BcalGetOp();
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, p.view);
        }
        $('.tg-today').css('background-color', '#fff');
        $(".calendar_color_guide").css('margin-left', '30px');
        $(".calendar_color_guide").css('margin-top', '0px');
        $(".calendar_color_guide").css('width', '658px');

        //var api = $('#dvtec').data('jsp');
        //                var time = new Date();
        //                var hour = time.getHours();
        //                if (hour > 12) hour = 12;
        //api.scrollTo(0, $("#hour_9").offset().top - 100);

    });
    //to show week view
    $("#btnWeek").click(function (e) {
        //document.location.href="#week";
        $("#nav_ca span.selected").each(function () {
            $(this).removeClass("selected");
        })
        $(this).addClass("selected");
        $("#gridcontainer").css('display', 'block');
        $("#listcontainer").css('display', 'none');

        var p = $("#gridcontainer").swtichView("week").BcalGetOp();
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, "week");
        }
        $(".calendar_color_guide").css('margin-left', '30px');
        $(".calendar_color_guide").css('margin-top', '0px');
        $(".calendar_color_guide").css('width', '658px');
        $("#tgnowptr").hide();

        //var api = $('#dvtec').data('jsp');
        //                var time = new Date();
        //                var hour = time.getHours();
        //                if (hour > 12) hour = 12;
        //api.scrollTo(0, $("#hour_9").offset().top - 200);
    });
    //to show month view
    $("#btnMonth").click(function (e) {
        //document.location.href="#month";
        $("#nav_ca span.selected").each(function () {
            $(this).removeClass("selected");
        })
        $(this).addClass("selected");
        $("#gridcontainer").css('display', 'block');
        $("#listcontainer").css('display', 'none');
        var p = $("#gridcontainer").swtichView("month").BcalGetOp();
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, p.view);
        }
        $(".calendar_color_guide").css('margin-left', '10px');
        $(".calendar_color_guide").css('margin-top', '19px');
        $(".calendar_color_guide").css('width', '674px');
    });

    $("#btnList").click(function (e) {
        $("#nav_ca span.selected").each(function () {
            $(this).removeClass("selected");
        });
        $(this).addClass("selected");
        $("#gridcontainer").css('display', 'none');
        $("#listcontainer").css('display', 'block');
        $(".calendar_color_guide").css('margin-left', '6px');
        $(".calendar_color_guide").css('width', '675px');
        $(".calendar_color_guide").css('margin-top', '0');
        var p = $("#gridcontainer").gotoDate().BcalGetOp();
        //var p = $("#gridcontainer").swtichView("month").BcalGetOp();
        var p = $("#gridcontainer").swtichView("day").BcalGetOp();
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, p.view);
        }
        if (arrText2 == 0) {
            arrText2 = getdataList();
        }
        var dates = p.datestrshow.split('-');

        var startdates = dates[0].split(' ');
        //showList(startdates[0] + ',' + startdates[1] + ',' + startdates[2]);
        //onclick rows list

        //$('.list1').jScrollPane({ animateScroll: true });
        //var time = new Date();
        //var date = time.getDate();
        //if (date > 12) hour = 12;
        //updatestatus();
        dateview = startdates[0] + ',' + startdates[1] + ',' + startdates[2];
        scrollalert(dateview);
        //$('.list1').css('overflow-y', 'hidden');
    });

    function parseDate(str) {
        return new Date(Date.parse(str));
    }
    function arraycontaint(arr, val) {
        var currentdate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
        var a = val.split('-');
        var es = new Date(parseInt(a[0], '10'), (parseInt(a[1], '10') - 1), parseInt(a[2], '10'));
        //alert(currentdate+"\n"+es);
        for (var i = 0; i < arr.length; i++) {

            if (arr[i] == val) {
                return true;
            }
        }
        return false;
    }
    var arrdates; // array dates exist events
    arrText2 = getdataList();
    function getdataList() {
        var arrText = new Array();
        arrdates = new Array();
        $.ajax({
            url: URL_DATA,
            crossDomain: "true",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            traditional: true,
            data: JSON.stringify(alertFilter),
            "dataType": 'json',
            success: function (data) {
                if (data.StatusCode == 200) {
                    //var shtml = '';
                    $.each(data.ReturnData, function (i, val) {
                        var o = new Object();
                        o.id = val.ID;
                        o.name = val.Name;
                        if (PAGE == 'PVQ' || PAGE == 'Win') {
                            o.id = val.Text2ID;
                            o.name = val.Text2Name;
                            o.type = val.Type;
                        }
                        o.campaign = val.CampaignSummary.Name;
                        var date = val.SendDate.substr(6).replace(')', '').replace('/', '');
                        var sendTime = new Date(parseInt(date));
                        var month = sendTime.getMonth() + 1;
                        if (month < 9) {
                            month = '0' + (sendTime.getMonth() + 1);
                        }
                        var day = sendTime.getDate();
                        if (day <= 9) {
                            day = '0' + sendTime.getDate();
                        }
                        var year = sendTime.getFullYear();
                        var hour = sendTime.getHours();
                        var minute = sendTime.getMinutes();
                        o.startdate = parseDate(month + "/" + day + "/" + year + " " + hour + ":" + minute);
                        o.enddate = parseDate(month + "/" + day + "/" + year + " " + (hour + 2) + ":" + minute);
                        o.color = val.CampaignSummary.ColorCode;
                        o.desc = "";

                        o.country = val.AlertCollectionSummary.Preference[0].Preference.Country.Name;
                        //o.country = "";
                        o.language = val.AlertCollectionSummary.Preference[0].Preference.Language.Name;
                        //o.language = "";
                        if (val.IsActive) {
                            if (!arraycontaint(arrdates, year + "-" + month + "-" + day)) {
                                arrdates.push(year + "-" + month + "-" + day); // add date to array date if not exits in array date event
                            }
                            arrText.push(o);
                        }
                    });
                    arrdates.sort();
                    //arrdate.reverse();

                }
            },
            error: function (jqXHR, textStatus) {
                if (isBug) {
                    alert("Error in " + URL_DATA);
                }
            }
        });

        return arrText;
    }
    function buildDayOnWeek(date) {
        var arr = date.split('-');
        var currentdate = new Date(parseInt(arr[0], '10'), (parseInt(arr[1], '10') - 1), parseInt(arr[2], '10'));
        var str = "";
        switch (currentdate.getDay()) {
            case 0:
                str = 'Monday ';
                break;
            case 1:
                str = 'Tuesday ';
                break;
            case 2:
                str = 'Wednesday ';
                break;
            case 3:
                str = 'Thursday ';
                break;
            case 4:
                str = 'Friday ';
                break;
            case 5:
                str = 'Saturday ';
                break;
            case 6:
                str = 'Sunday ';
                break;
        }

        switch (currentdate.getMonth()) {
            case 0:
                str = str + 'January';
                break;
            case 1:
                str = str + 'February';
                break;
            case 2:
                str = str + 'March';
                break;
            case 3:
                str = str + 'April';
                break;
            case 4:
                str = str + 'May';
                break;
            case 5:
                str = str + 'June';
                break;
            case 6:
                str = str + 'July';
                break;
            case 7:
                str = str + 'August';
                break;
            case 8:
                str = str + 'September';
                break;
            case 9:
                str = str + 'October';
                break;
            case 10:
                str = str + 'November';
                break;
            case 11:
                str = str + 'December';
                break;
        }
        var day2 = currentdate.getDate() + 'th';

        if (currentdate.getDate() == 1) {

            day2 = currentdate.getDate() + 'st';
        }
        if (currentdate.getDate() == 2) {
            day2 = currentdate.getDate() + 'nd';
        }
        if (currentdate.getDate() == 3) {
            day2 = currentdate.getDate() + 'rd';
        }
        str = str + ' ' + day2;

        return str;
    }
    var countItems = 0;
    function updatestatus() {
        //Show number of loaded items
        //var totalItems = $('#list li').length - $('#list li li').length;
        $('#status').text('Loaded ' + countItems + ' Items');
    }
    function scrollalert(daystart) {
        //        var scrolltop = $('#list')[0].offsetParent.style.top.replace('px','');
        //        var scrollheight = $(".jspPane").css('height');
        var windowheight = $('#list').attr('clientHeight');
        //var scrolloffset = 20;

        //if (countItems == 0) {
        //fetch new items
        //$('#status').text('Loading more items...');
        //        $.get('new-items.html', '', function (newitems) {
        //            $('#list').append(newitems);
        //            updatestatus();
        //        });


        if (countItems == 0) {
            $('#list ul#ullist').html(showList(daystart, 10));
            //$('.list_footer').css('display', 'block');
        }
        else {
            if (countItems <= arrdates.length) {
                $('#list ul#ullist').append(showList(daystart, 10));
            }
        }
        if ($('.list_footer').css('display') == 'none') {

            $('.list1').bind(
				    'jsp-scroll-y',
				    function (event, scrollPositionY, isAtTop, isAtBottom) {
				        if (isAtBottom) {
				            if (countItems < arrdates.length - 2) {
				                scrollalert(dateview);
				                $('.list1').data('jsp').scrollTo(0, windowheight - scrollPositionY);
				            }
				        }
				    }
			    ).jScrollPane({ animateScroll: true });
        }
        $(".rowlist").click(function (e) {
            if (PAGE == 'Alert') {
                rowlistshow(e, $(this).attr('id'), $(this).html(), 'Alert');
            }
            else {
                rowlistshow(e, $(this).attr('id'), $(this).html(), $(this).attr('type'));
            }
        });


    }

    function showList(startdate, numrows) {

        //var strrows = '<div><ul>';
        var strrows = "";
        var dateEx = new Date(startdate);

        //var startdate2 = dateEx.getFullYear() + '-' + (dateEx.getMonth() + 1) + '-' + dateEx.getDate();
        //var d = new Date(now);
        //alert(arrdates.length);
        var descountItem = countItems + 10;
        if (descountItem > arrdates.length) {
            descountItem = arrdates.length;
        }
        //alert(countItems + '-' + descountItem);
        //alert(descountItem);
        for (var i = countItems; i < descountItem; i++) {
            var rowday = "";
            var arrdate1 = arrdates[i].split('-');
            var date1 = new Date(parseInt(arrdate1[0], '10'), parseInt(arrdate1[1], '10') - 1, parseInt(arrdate1[2], '10'));
            if (date1 >= dateEx) {
                var titledate = buildDayOnWeek(arrdates[i]);
                rowday = rowday + '<li id="row' + arrdates[i] + '"><a hef="#">' + titledate + '</a>';
                var co2 = 0;

                for (var k = 0; k < arrText2.length; k++) {

                    var day = parseDate(arrText2[k].startdate).getDate();
                    if (day <= 9) {
                        day = '0' + day;
                    }
                    var mon = parseDate(arrText2[k].startdate).getMonth() + 1;
                    if (mon <= 9) {
                        mon = '0' + mon;
                    }
                    var year = parseDate(arrText2[k].startdate).getFullYear();
                    var hour = parseDate(arrText2[k].startdate).getHours();
                    var minute = parseDate(arrText2[k].startdate).getMinutes();
                    if (minute < 9) {
                        minute = '0' + minute;
                    }
                    var starttime = year + '-' + mon + '-' + day;

                    if (starttime == arrdates[i]) {
                        //isExitEvent = true;
                        //alert(hour + minute + " " + dateFormat(arrText2[k].startdate, 'isoDate') + "-" + NextDate)
                        if (co2 == 0) {
                            rowday = rowday + "<ul>";
                            co2++;
                        }
                        rowday = rowday + '<li><a type="' + arrText2[k].type + '" id="' + arrText2[k].id + '" class="rowlist one" style="background:' + arrText2[k].color + '">' + hour + ":" + minute + ' - ' + arrText2[k].campaign + ', ' + arrText2[k].name + ' (' + arrText2[k].country + '/' + arrText2[k].language + ')</a></li>';
                    }
                }
                if (co2 > 0) {
                    rowday = rowday + "</ul></li>";
                }
                else {
                    rowday = rowday + "</li>";
                }
                strrows = strrows + rowday;
            }
        }
        //strrows = strrows + '</ul></div>';


        countItems = descountItem;
        return strrows;
    }

    $("#showreflashbtn").click(function (e) {
        $("#gridcontainer").reload();
    });
    var dateview; // date selected
    $("#btnMore").click(function (e) {
        if (countItems > 0) {
            countItems = countItems + 10;
            scrollalert(dateview);
            $('.list1').bind(
				'jsp-scroll-y',
				function (event, scrollPositionY, isAtTop, isAtBottom) {
				    if (isAtBottom) {
				        if (countItems < arrdates.length - 2) {
				            scrollalert(dateview);
				            $('.list1').data('jsp').scrollTo(0, windowheight - scrollPositionY);
				        }
				    }
				}
			).jScrollPane({ animateScroll: true });
        }
        $('.list_footer').css('display', 'none');
    });
    //Add a new event
    $("#faddbtn").click(function (e) {
        var url = "edit.php";
        OpenModelWindow(url, { width: 500, height: 400, caption: "Create New Calendar" });
    });
    //go to today
    $("#btnToday").click(function (e) {
        var p = $("#gridcontainer").gotoDate().BcalGetOp();
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, p.view);
        }
        var dates = p.datestrshow.split('-');
        var startdates = dates[0].split(' ');

        //showList(startdates[0] + ',' + startdates[1] + ',' + startdates[2]);
        countItems = 0;
        dateview = startdates[0] + ',' + startdates[1] + ',' + startdates[2];
        scrollalert(dateview);
        //                var api = $('#dvtec').data('jsp');
        //                var time = new Date();
        //                var hour = time.getHours();
        //                if (hour > 12) hour = 12;
        $('.tg-today').css('background-color', '#fff');

    });
    //previous date range
    $("#btnPreCa").click(function (e) {
        var p = $("#gridcontainer").previousRange().BcalGetOp();
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, p.view);

        }
        var dates = p.datestrshow.split('-');
        var startdates = dates[0].split(' ');
        //showList(startdates[0] + ',' + startdates[1] + ',' + startdates[2]);
        //$('.list1').jScrollPane({ animateScroll: true });
        countItems = 0;
        dateview = startdates[0] + ',' + startdates[1] + ',' + startdates[2];
        scrollalert(dateview);
    });
    //next date range

    $("#btnNextCa").click(function (e) {
        var p = $("#gridcontainer").nextRange().BcalGetOp();
        if (p && p.datestrshow) {
            updateDate(p.datestrshow, p.view);
        }
        var dates = p.datestrshow.split('-');
        var startdates = dates[0].split(' ');
        //showList(startdates[0] + ',' + startdates[1] + ',' + startdates[2]);
        //$('.list1').jScrollPane({ animateScroll: true });
        countItems = 0;
        dateview = startdates[0] + ',' + startdates[1] + ',' + startdates[2];
        scrollalert(dateview);
    });

    $("#checkall").click(function () {
        $('.case').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearall").click(function () {
        $('.case').removeAttr('checked');
        setupLabel();

    });
    //$('.list_countries').jScrollPane({ animateScroll: true });
    $('.ddlcountries').hide();
    $('.countries').hide();
    $('.btn_countries').click(function () {
        if ($('.countries').css('display') == 'none') {
            $('.countries').show();
        } else {
            $('.countries').hide();
        }
    });

    $("#checkallType").click(function () {
        $('.case_type').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearallType").click(function () {
        $('.case_type').removeAttr('checked');
        setupLabel();
    });
    $('.list_type').jScrollPane({ animateScroll: true });
    $('.ddltype').hide();
    $('.type').hide();
    $('.btn_type').click(function () {
        if ($('.type').css('display') == 'none') {
            $('.type').show();
        } else {
            $('.type').hide();
        }
    });

    $("#checkallCampaign").click(function () {
        $('.case_campaign').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearallCampaign").click(function () {
        $('.case_campaign').removeAttr('checked');
        setupLabel();
    });
    //$('.list_campaign').jScrollPane({ animateScroll: true });
    $('.ddlcampaign').hide();
    $('.campaign').hide();
    $('.btn_campaign').click(function () {
        if ($('.campaign').css('display') == 'none') {
            $('.campaign').show();
        } else {
            $('.campaign').hide();
        }
    });

    // Custom drop down list Language
    $("#checkallLanguage").click(function () {
        $('.case_language.case_main').attr('checked', 'checked');
        setupLabel();
    });
    $("#clearallLanguage").click(function () {
        $('.case_language.case_main').removeAttr('checked');
        setupLabel();
    });
    $('.ddllanguage').hide();
    $('.language').hide();
    $('.btn_language').click(function () {
        if ($('.language').css('display') == 'none') {
            $('.language').show();
            $('.list_language').jScrollPane();
        } else {
            $('.language').hide();
        }
    });
    // End Custom drop down list Language

    $('body').addClass('has-js');
    $('.label_check, .label_radio, .label_check_ip').click(function () {
        setupLabel();
    });
    setupLabel();
    //$('select.select_countries').customStyle();    



    $("#btclearall").click(function () {
        $("#fitlers").find(".itemfilter").each(function (index) {
            if ($(this).attr("id") != "itemfiltertemplate") {
                $(this).remove();
            }
        });
        campaignids.splice(0, campaignids.length);
        alertFilter.campaignid = campaignids;

        messagebodys.splice(0, messagebodys.length);
        alertFilter.messagebody = messagebodys;

        alertnames.splice(0, alertnames.length);
        alertname.messagebody = alertnames;

        languageids.splice(0, languageids.length);
        alertname.languageid = languageids;

        campaignids.splice(0, campaignids.length);
        alertname.campaignid = campaignids;
        filterData();
        $("#fitlers").css("height", 4);
    });
    function filterData() {

        if (arrPage[arrPage.length - 1] == "Alert") {
            PAGE = 'Alert';
            URL_DATA = gb_servicePath + '/alertinstance/list/summary.json';
        }
        else if (arrPage[arrPage.length - 1] == "PVQ") {
            URL_DATA = gb_servicePath + '/text2/list/summary.json';
            PAGE = 'PVQ';
        }
        else {
            URL_DATA = gb_servicePath + '/text2/list/summary.json';
            PAGE = 'Win';
        }
        if ($("#btnList").hasClass('selected')) {
            arrText2 = new Array();
            arrText2 = getdataList();

            var p = $("#gridcontainer").swtichView("week").BcalGetOp();

            if (p && p.datestrshow) {
                updateDate(p.datestrshow, p.view);
            }

            var dates = p.datestrshow.split('-');

            var startdates = dates[0].split(' ');
            dateview = startdates[0] + ',' + startdates[1] + ',' + startdates[2];
            scrollalert(dateview);

        }
        else {

            var op = {
                view: view,
                theme: 3,
                height: 420,
                showday: new Date(),
                EditCmdhandler: Edit,
                DeleteCmdhandler: Delete,
                ViewCmdhandler: View,
                onWeekOrMonthToDay: wtd,
                onBeforeRequestData: cal_beforerequest,
                onAfterRequestData: cal_afterrequest,
                onRequestDataError: cal_onerror,
                autoload: true,
                url: URL_DATA,
                quickAddUrl: DATA_FEED_URL + "/addEvent",
                quickUpdateUrl: DATA_FEED_URL + "/updateEvent",
                quickDeleteUrl: DATA_FEED_URL + "/removeEvent",
                filter: alertFilter,
                viewpage: PAGE
            };
            var $dv = $("#calhead");
            var _MH = document.documentElement.clientHeight;
            var dvH = $dv.height() + 2;
            //op.height = _MH - dvH;
            op.eventItems = [];
            var p = $("#gridcontainer").bcalendar(op).BcalGetOp();
            if ($("#btnDay").hasClass('selected')) {
                p = $("#gridcontainer").swtichView("day").BcalGetOp();
            }
            if ($("#btnWeek").hasClass('selected')) {
                p = $("#gridcontainer").swtichView("week").BcalGetOp();
            }
            if ($("#btnMonth").hasClass('selected')) {
                p = $("#gridcontainer").swtichView("month").BcalGetOp();

            }
            if (p && p.datestrshow) {
                updateDate(p.datestrshow, p.view);
            }
        }
        //$('.list1').jScrollPane({ animateScroll: true });
    }
    $('#btnGo').click(function () {
        if (PAGE == 'Alert') {// search by Alert
            if ($("#filterSearch").val() != "") {
                addItemFilterName($("#filterSearch").val());
                //alert names to filter

                alertnames.push($("#filterSearch").val());
                alertFilter.alertname = alertnames;
                $("#filterSearch").val("");
            }
            if ($("#txtMessage").val() != "") {
                addItemFilterMessage($("#txtMessage").val());
                //messagebody to filter

                messagebodys.push("1");
                alertFilter.messagebody = messagebodys;
                $("#txtMessage").val("");
            }
            if ($(".campaign input:checked").length > 0) {
                var arr = $(".campaign input:checked").getCheckboxVal();
                //campaign to filter
                campaignids.push("1");
                alertFilter.campaignid = campaignids;

                addItemFilterCampaign(arr.join(' OR '));
            }
            if ($(".countries input:checked").length > 0) {
                var arr = $(".countries input:checked").getCheckboxVal();
                //country to filter
                countryids.push("5");
                alertFilter.countryid = countryids;
                addItemFilterCountry(arr.join(' OR '));
            }
        }
        else if (PAGE == 'PVQ') {
            if ($("#filterSearch").val() != "") {
                addItemFilterName($("#filterSearch").val());
                //alert names to filter

                alertnames.push($("#filterSearch").val());
                alertFilter.alertname = alertnames;
                $("#filterSearch").val("")
            }
            if ($("#txtMessage").val() != "") {
                addItemFilterMessage($("#txtMessage").val());
                //messagebody to filter

                messagebodys.push($("#txtMessage").val());
                alertFilter.messagebody = messagebodys;
                $("#txtMessage").val("")
            }
            if ($(".campaign input:checked").length > 0) {
                var arr = $(".campaign input:checked").getCheckboxVal();
                var arrName = $(".campaign input:checked").getCheckboxName();
                campaignids.splice(0, campaignids.length);
                //campaign to filter
                for (i = 0; i < arrName.length; i++) {
                    campaignids.push(arrName[i]);
                }
                alertFilter.campaignid = campaignids;
                addItemFilterCampaign(arr.join(' <i>OR</i> '));
            }
            if ($(".type input:checked").length > 0) {
                var arr = $(".type input:checked").getCheckboxVal();
                var arrName = $(".type input:checked").getCheckboxName();
                //country to filter
                Text2ComponentIDs.splice(0, Text2ComponentIDs.length);
                for (i = 0; i < arrName.length; i++) {
                    Text2ComponentIDs.push(arrName[i]);
                }
                alertFilter.Text2ComponentIDs = Text2ComponentIDs; // search by Type = PVQ

                addItemFilterType(arr.join(' <i>OR</i> '));
            }
            if ($(".countries input:checked").length > 0) {
                var arr = $(".countries input:checked").getCheckboxVal();
                var arrName = $(".countries input:checked").getCheckboxName();
                //country to filter
                countryids.splice(0, countryids.length);
                for (i = 0; i < arrName.length; i++) {
                    countryids.push(arrName[i]);
                }
                alertFilter.countryid = countryids;
                addItemFilterCountry(arr.join(' <i>OR</i> '));
            }
            if ($(".language input:checked").length > 0) {
                var arr = $(".language input:checked").getCheckboxVal();
                //language to filter
                languageids.splice(0, languageids.length);
                for (i = 0; i < arrName.length; i++) {
                    languageids.push(arrName[i]);
                }
                alertFilter.languageid = languageids;
                addItemFilterLanguage(arr.join(' <i>OR</i> '));
            }
        }
        else {
            if ($("#filterSearch").val() != "") {
                addItemFilterName($("#filterSearch").val());
                //alert names to filter

                alertnames.push($("#filterSearch").val());
                alertFilter.alertname = alertnames;
                $("#filterSearch").val("")
            }
            if ($("#txtMessage").val() != "") {
                addItemFilterMessage($("#txtMessage").val());
                //messagebody to filter

                messagebodys.push($("#txtMessage").val());
                alertFilter.messagebody = messagebodys;
                $("#txtMessage").val("")
            }
            if ($(".campaign input:checked").length > 0) {
                var arr = $(".campaign input:checked").getCheckboxVal();
                var arrName = $(".campaign input:checked").getCheckboxName();
                campaignids.splice(0, campaignids.length);
                //campaign to filter
                for (i = 0; i < arrName.length; i++) {
                    campaignids.push(arrName[i]);
                }
                alertFilter.campaignid = campaignids;
                addItemFilterCampaign(arr.join(' <i>OR</i> '));
            }


            Text2ComponentIDs.push('5'); // search by Type = Win
            alertFilter.Text2ComponentIDs = Text2ComponentIDs;

            if ($(".countries input:checked").length > 0) {
                var arr = $(".countries input:checked").getCheckboxVal();
                var arrName = $(".countries input:checked").getCheckboxName();
                //country to filter
                countryids.splice(0, countryids.length);
                for (i = 0; i < arrName.length; i++) {
                    countryids.push(arrName[i]);
                }
                alertFilter.countryid = countryids;
                addItemFilterCountry(arr.join(' <i>OR</i> '));
            }
            if ($(".language input:checked").length > 0) {
                var arr = $(".language input:checked").getCheckboxVal();
                //language to filter
                languageids.splice(0, languageids.length);
                for (i = 0; i < arrName.length; i++) {
                    languageids.push(arrName[i]);
                }
                alertFilter.languageid = languageids;
                addItemFilterLanguage(arr.join(' <i>OR</i> '));
            }
        }
        filterData();
    });

    $('#ddlFilter').change(function () {
        if ($(this).val() == "Name") {
            $('.type_filter').addClass('hide');
            $('#AlertName').removeClass('hide');
            $('#lblFilter').text('Contains');
        }
        if ($(this).val() == "Campaign") {
            $('.type_filter').addClass('hide');
            $('.ddlcampaign').removeClass('hide');
            $('.ddlcampaign').css('display', 'inline-block');
            $('#lblFilter').text('Is');
        }
        if ($(this).val() == "Type") {
            $('.type_filter').addClass('hide');
            $('.ddltype').removeClass('hide');
            $('.ddltype').css('display', 'inline-block');
            $('#lblFilter').text('Is');
        }
        if ($(this).val() == "Country") {
            $('.type_filter').addClass('hide');
            $('.ddlcountries').removeClass('hide');
            $('.ddlcountries').css('display', 'inline-block');
            $('#lblFilter').text('Is');
        }
        if ($(this).val() == "Language") {
            $('.type_filter').addClass('hide');
            $('.ddllanguage').removeClass('hide');
            $('.ddllanguage').css('display', 'inline-block');
            $('#lblFilter').text('Is');
        }
        if ($(this).val() == "Message") {
            $('.type_filter').addClass('hide');
            $('#Message').removeClass('hide');
            $('#lblFilter').text('Contains');
        }
    });



    function addItemFilterCountry(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Country IS ' + str);
        $(o).attr("id", "itemFilterCountry");
        if ($('#itemFilterCountry').length) {
            $("#itemFilterCountry .filertext").html('Country IS ' + str);
        }
        else {
            $("#fitlers").append(o);
        }
        //$(o).css("width", $(o).find(".filertext").outerWidth() + 25);

        //add event listener
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            countryids.splice(0, countryids.length);
            alertFilter.countryid = countryids;
            filterData();

        });

    }
    function addItemFilterLanguage(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Language IS ' + str);
        $(o).attr("id", "itemFilterLanguage");
        if ($('#itemFilterLanguage').length) {
            $("#itemFilterLanguage .filertext").html('Language IS ' + str);
            filterData();

        }
        else {
            $("#fitlers").append(o);
        }
        //$(o).css("width", $(o).find(".filertext").outerWidth() + 25);

        //add event listener
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            languageids.splice(0, languageids.length);
            alertFilter.languageid = languageids;
            filterData();

        });

    }
    function addItemFilterType(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Type = ' + str);
        $(o).attr("id", "itemFilterType");
        if ($('#itemFilterType').length) {
            $("#itemFilterType .filertext").html('Type = ' + str);
        }
        else {
            $("#fitlers").append(o);
        }
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
        });

    }
    function addItemFilterCampaign(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Campaign IS ' + str);
        $(o).attr("id", "itemFilterCampaign");
        if ($('#itemFilterCampaign').length) {
            $("#itemFilterCampaign .filertext").html('Campaign IS ' + str);
        }
        else {
            $("#fitlers").append(o);
        }
        //$(o).css("width", $(o).find(".filertext").outerWidth() + 25);

        //add event listener
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            campaignids.splice(0, campaignids.length);
            alertFilter.campaignid = campaignids;
            filterData();

        });

    }
    function addItemFilterName(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Name contains "' + str + '"');
        $(o).attr("id", "itemFilterName");
        if ($('#itemFilterName').length) {
            $("#itemFilterName").append($(o).find(".filertext").html('&nbsp;OR "' + str + '"'));
        }
        else {
            $("#fitlers").append(o);
        }
        //$(o).css("width", $(o).find(".filertext").outerWidth() + 25);

        //add event listener
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            alertnames.splice(0, alertnames.length);
            alertFilter.alertname = alertnames;
            filterData();

        });

    }
    function addItemFilterMessage(str) {
        var o = $("#itemfiltertemplate").clone();
        $(o).find(".filertext").html('Message contains "' + str + '"');
        $(o).attr("id", "itemFilterMessage");
        if ($('#itemFilterMessage').length) {
            var filterFirsr = $("#itemFilterMessage .filertext:first").text();
            $("#itemFilterMessage").append($(o).find(".filertext").html('&nbsp;Or "' + str + '"'));
        }
        else {
            $("#fitlers").append(o);
        }
        //$(o).css("width", $(o).find(".filertext").outerWidth() + 25);

        //add event listener
        $(o).find(".btfilterclose").click(function () {
            $(this).parent().remove();
            messagebodys.splice(0, messagebodys.length);
            alertFilter.messagebody = messagebodys;
            filterData();
        });

    }

    function updateDate(value, view) {
        var dates = value.split('-');
        var startdates = dates[0].split(' ');

        var strOut = startdates[0] + " " + startdates[1];

        if (dates.length > 1) {
            var enddates = $.trim(dates[1]).split(' ');
            strOut += " - " + enddates[0] + " " + enddates[1];
        }

        if (view == "month") {
            var start_date = new Date(dates[0]);
            var start_day = start_date.getDate();
            if (start_day > 15) {
                start_date.setDate(start_date.getDate() + 15);
                //strOut = $.datepicker.formatDate('MM yy', start_date);

                var date1 = new Date(start_date);
                switch (date1.getMonth()) {
                    case 0:
                        strOut = 'January ' + date1.getFullYear();
                        break;
                    case 1:
                        strOut = 'February ' + date1.getFullYear();
                        break;
                    case 2:
                        strOut = 'March ' + date1.getFullYear();
                        break;
                    case 3:
                        strOut = 'April ' + date1.getFullYear();
                        break;
                    case 4:
                        strOut = 'May ' + date1.getFullYear();
                        break;
                    case 5:
                        strOut = 'June ' + date1.getFullYear();
                        break;
                    case 6:
                        strOut = 'July ' + date1.getFullYear();
                        break;
                    case 7:
                        strOut = 'August ' + date1.getFullYear();
                        break;
                    case 8:
                        strOut = 'September ' + date1.getFullYear();
                        break;
                    case 9:
                        strOut = 'October ' + date1.getFullYear();
                        break;
                    case 10:
                        strOut = 'November ' + date1.getFullYear();
                        break;
                    case 11:
                        strOut = 'December ' + date1.getFullYear();
                        break;
                }
                console.log(strOut);
            } else {
                strOut = startdates[0];
            }
        }

        if (startdates.length == 3) {
            if (view != "month") {
                strOut += ", " + startdates[2];
            }
        }
        $("#txtdatetimeshow").text(strOut);
    }
    //var selectedRowKey = ""; // row's id is current selected in list 
    ///onclick rows list
    function rowlistshow(e, aid, title, type) {
        //var clientX = e.clientX;
        var clientY = e.clientY;
        //var left = clientX - 510;
        var top = clientY - 350;
        if (top < -60) {
            top = -60;
        }
        //alert(clientY);
        // show sumary popup
        $('#view_summary').removeClass('hide');
        if (type == 'Alert') {
            $('.list_mess_main').remove();
            GetDetailSummaryForAlert(aid, title);
        }
        else {
            $('.list_mess_main').remove();
            GetDetailSummaryForPVQWIN(aid, title, type);
        }
        $('.list_row_alert').jScrollPane({ animateScroll: true });

        $("#view_summary").css('position', 'absolute');
        //.css('margin', top+'px 0 0 '+left+'px');
        $("#view_summary").css('top', top + 'px');
        $("#view_summary").css('right', '80px');
        $("#view_summary").css('z-index', '999');
        //        $('.list_messages_summary ').css('height', '100px');
        //        $('.list_messages_summary').css('overflow', 'hidden');
        $('.btn_close').click(function (e) {
            $("#view_summary").addClass('hide');
            return false;
        });
        return false;
    }
    // Function Get Detail Summary for Alert
    function GetDetailSummaryForAlert(id, title) {

        $.getJSON(gb_servicePath + '/alertinstance/ID/' + id + '.json',
            {},
            function (json) {
                if (json.StatusCode == 200) {
                    var shtml = '';
                    var data = json.ReturnData;
                    title = title.split(',')[1];
                    $('#header_box_super_admin').html(title);
                    $('#campaign_name').html(data.AlertInstanceSummary.CampaignSummary.Name);

                    var start_time = data.AlertInstanceSummary.AlertCollectionSummary.StartTime.substr(6).replace(')', '').replace('/', '');
                    var end_time = data.AlertInstanceSummary.AlertCollectionSummary.EndTime.substr(6).replace(')', '').replace('/', '');
                    //alert(parseInt(date));05/01/2011 15:36
                    start_time = new Date(parseInt(start_time));
                    start_time = format2Digi(start_time.getMonth() + 1) + '/' + format2Digi(start_time.getDate()) + '/' + start_time.getFullYear() + ' ' + format2Digi(start_time.getHours()) + ':' + format2Digi(start_time.getMinutes());
                    end_time = new Date(parseInt(end_time));
                    end_time = format2Digi(end_time.getMonth() + 1) + '/' + format2Digi(end_time.getDate()) + '/' + end_time.getFullYear() + ' ' + format2Digi(end_time.getHours()) + ':' + format2Digi(end_time.getMinutes());
                    $('#start_date').html(start_time);
                    $('#end_date').html(end_time);

                    var frequency = "";
                    if (data.AlertInstanceSummary.AlertCollectionSummary.FrequencySettings.length > 0) {
                        var Timeunitid = data.AlertInstanceSummary.AlertCollectionSummary.FrequencySettings[0].Timeunitid;
                        switch (Timeunitid) {
                            case 1:
                                frequency = "Minute";
                                break;
                            case 2:
                                frequency = "Hour";
                                break;
                            case 3:
                                frequency = "Daily";
                                break;
                            case 4:
                                frequency = "Week";
                                break;
                            case 5:
                                frequency = "Month";
                                break;
                            case 6:
                                frequency = "Year";
                                break;
                        }
                    }
                    else {
                        frequency = "None";
                    }
                    $('#recurring').html(frequency);

                    //$('#countries').html(data.Alertcollection.Preference.each(data.Alertcollection.Preference, function (country) { return country.Name + ', ' }))
                    var country = "";
                    var countryIds = "";
                    var delivery = "";
                    var deliveryIds = "";
                    $.each(data.AlertInstanceSummary.AlertCollectionSummary.Preference, function (i, val) {
                        if (countryIds.indexOf(val.Preference.Country.Id) == -1) {
                            country += val.Preference.Country.Name + " ( " + val.Preference.Language.Name + " ) " + "<br/>"
                            countryIds += val.Preference.Country.Id + ",";
                        }
                        if (deliveryIds.indexOf(val.Media.Id) == -1) {
                            delivery += val.Media.Name + ",";
                            deliveryIds += val.Media.Id + ",";
                        }
                    });

                    $('#countries').html(country);
                    $('#delivery').html(delivery.substring(0, delivery.length - 1));
                    var audience = "";
                    $.each(data.Alertcollection.Audience, function (i, val) {
                        audience += val.Name + ",";
                    })
                    $("#audience").html(audience.substring(0, audience.length - 1));

                    $(".messagesTemplate").css("display", "none");
                    $.each(data.AlertInstanceSummary.MessageFlows, function (i1, val1) {
                        var o = $(".messagesTemplate").clone();
                        $(o).removeClass("messagesTemplate");
                        $(o).addClass('list_mess_main');
                        $(o).css("display", "block");
                        $(o).attr('id', 'id' + val1.Id);
                        $(o).find(".lblMessage").html(val1.Country.Name + '/' + val1.Language.Name + '/' + val1.Media.Name);
                        $(o).find(".lbl_content_mess").html(val1.Messagebody);

                        $.each(val1.KeywordIDList, function (i2, val2) {
                            var id = val2;
                            var str = "";
                            $.getJSON(gb_servicePath + '/keyword/ID/' + id + '.json',
                                {},
                                function (json) {
                                    if (json.StatusCode == 200) {
                                        var data = json.ReturnData;
                                        str = str + "<div class=\"list_keyword_main\"><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">" +
                                        "<tr><td><b>Keyword</b></td><td class=\"lblKeyword\">" + data.Name + "</td></tr>";
                                        $.each(data.Audience, function (i3, val3) {
                                            str = str + "<tr><td><b>Audience</b></td><td class=\"lblAudience\">" + val3.Name + "</td></tr>";
                                        });
                                        str = str + "</table><div class=\"list_mess_type\">";
                                        $.each(data.FollowUpMessageFlowList, function (i4, val4) {
                                            str = str + "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\"><tr><td width=\"100%\">" +
                                            "<b class=\"lbl_for_mess_type\">Message for Message Type " + (i4 + 1) + "</b>" +
                                            "<div id=\"contentMessageType\" class=\"contentMessageType\">" + val4.Messagebody +
                                            "</div></td></tr>";
                                        });
                                        str = str + "</div></div>";
                                        $('#id' + val1.Id + ' .list_keyword').append(str);
                                    }

                                });
                            //$('.list_keyword').html(str);
                        });

                        $("#content_mess .jspPane").append(o);
                        $('#content_mess').jScrollPane({ animateScroll: true });
                        $('.expand_mess_flow').click(function () {
                            $(this).addClass('hide');
                            $(this).next().removeClass('hide');
                            $(this).prev().removeClass('hide');
                            $('#content_mess').jScrollPane({ animateScroll: true });
                        });
                        $('.collapse_mess_flow').click(function () {
                            $(this).addClass('hide');
                            $(this).prev().removeClass('hide');
                            $(this).prev().prev().addClass('hide');
                            $('#content_mess').jScrollPane({ animateScroll: true });
                        });
                    });
                }
            }
            );
    }

    function GetDetailSummaryForPVQWIN(id, title, type) {
        $.getJSON(gb_servicePath + '/Text2/ID/' + id + '.json?type=' + type,
            {},
            function (json) {
                if (json.StatusCode == 200) {
                    var shtml = '';
                    var data = json.ReturnData;

                    $('#type_name').html(data.Component.Name);
                    $('#header_box_super_admin').html(data.Name);
                    var start_time = data.StartTime.substr(6).replace(')', '').replace('/', '');
                    var end_time = data.EndTime.substr(6).replace(')', '').replace('/', '');
                    //alert(parseInt(date));05/01/2011 15:36
                    start_time = new Date(parseInt(start_time));
                    start_time = format2Digi(start_time.getMonth() + 1) + '/' + format2Digi(start_time.getDate()) + '/' + start_time.getFullYear() + ' ' + format2Digi(start_time.getHours()) + ':' + format2Digi(start_time.getMinutes());
                    end_time = new Date(parseInt(end_time));
                    end_time = format2Digi(end_time.getMonth() + 1) + '/' + format2Digi(end_time.getDate()) + '/' + end_time.getFullYear() + ' ' + format2Digi(end_time.getHours()) + ':' + format2Digi(end_time.getMinutes());
                    $('#send_on').html(start_time);
                    $('#valid_until').html(end_time);
                    $('#campaign_name').html(data.Campaign.Name);


                    //$('#countries').html(data.Alertcollection.Preference.each(data.Alertcollection.Preference, function (country) { return country.Name + ', ' }))
                    var country = "";
                    var countryIds = "";
                    var delivery = "";
                    var deliveryIds = "";
                    $.each(data.Preference, function (i, val) {
                        if (countryIds.indexOf(val.Preference.Country.Id) == -1) {
                            country += val.Preference.Country.Name + " ( " + val.Preference.Language.Name + " ) " + "<br/>"
                            countryIds += val.Preference.Country.Id + ",";
                        }
                        if (deliveryIds.indexOf(val.Media.Id) == -1) {
                            delivery += val.Media.Name + ",";
                            deliveryIds += val.Media.Id + ",";
                        }
                    });

                    $('#countries').html(country);
                    $('#delivery').html(delivery.substring(0, delivery.length - 1));
                    var audience = "";
                    $.each(data.Audience, function (i, val) {
                        audience += val.Name + ",";
                    })
                    $("#audience").html(audience.substring(0, audience.length - 1));


                    $(".messagesTemplate").css("display", "none");
                    $.each(data.MessageFlows, function (val1, val1) {
                        var o = $(".messagesTemplate").clone();
                        $(o).removeClass("messagesTemplate");
                        $(o).addClass('list_mess_main');
                        $(o).css("display", "block");
                        $(o).attr('id', 'id' + val1.Id);
                        $(o).find(".lblMessage").html(val1.Country.Name + '/' + val1.Language.Name + '/' + val1.Media.Name);
                        $(o).find(".lbl_content_mess").html(val1.Messagebody);
                        $.each(val1.KeywordIDList, function (i2, val2) {
                            var id = val2;
                            var str = "";
                            $.getJSON(gb_servicePath + '/keyword/ID/' + id + '.json',
                                {},
                                function (json) {
                                    if (json.StatusCode == 200) {
                                        var data = json.ReturnData;
                                        str = str + "<div class=\"list_keyword_main\"><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">" +
                                        "<tr><td><b>Keyword</b></td><td class=\"lblKeyword\">" + data.Name + "</td></tr>";
                                        $.each(data.Audience, function (i3, val3) {
                                            str = str + "<tr><td><b>Audience</b></td><td class=\"lblAudience\">" + val3.Name + "</td></tr>";
                                        });
                                        str = str + "</table><div class=\"list_mess_type\">";
                                        $.each(data.FollowUpMessageFlowList, function (i4, val4) {
                                            str = str + "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\"><tr><td width=\"100%\">" +
                                            "<b class=\"lbl_for_mess_type\">Message for Message Type " + (i4 + 1) + "</b>" +
                                            "<div id=\"contentMessageType\" class=\"contentMessageType\">" + val4.Messagebody +
                                            "</div></td></tr>";
                                        });
                                        str = str + "</div></div>";
                                        $('#id' + val1.Id + ' .list_keyword').append(str);
                                    }

                                });
                            //$('.list_keyword').html(str);
                        });
                        $("#content_mess .jspPane").append(o);
                        $('#content_mess').jScrollPane({ animateScroll: true });
                        $('.expand_mess_flow').click(function () {
                            $(this).addClass('hide');
                            $(this).next().removeClass('hide');
                            $(this).prev().removeClass('hide');
                            $('#content_mess').jScrollPane({ animateScroll: true });
                        });
                        $('.collapse_mess_flow').click(function () {
                            $(this).addClass('hide');
                            $(this).prev().removeClass('hide');
                            $(this).prev().prev().addClass('hide');
                            $('#content_mess').jScrollPane({ animateScroll: true });
                        });

                    });

                }
            }
            );
    }
    // Function format number
    function format2Digi(num) {
        if (num > 9) return num;
        else return "0" + num + 1;
    }
    // End Function format number
});
